Hoisting is a JavaScript mechanism where variables and function declarations are moved (hoisted) to the top of their scope before the code execution. This means that you can use variables and functions before declaring them in your code.
However, only declarations are hoisted, not initializations.
var
Explanation:
var x;
is hoisted to the top, but the assignment x = 5;
is not.console.log(x);
before initialization prints undefined
.let
and const
Explanation:
var
, let
and const
are hoisted but remain in a "temporal dead zone" (TDZ) until their declaration is encountered.y
before it's declared.
Explanation:
Explanation:
greet
is hoisted as undefined
, so calling it before initialization causes an error.Type | Hoisted? | Usable Before Declaration? |
---|---|---|
var | ✅ Yes | ⚠️ Yes, but undefined |
let | ✅ Yes | ❌ No (TDZ Error) |
const | ✅ Yes | ❌ No (TDZ Error) |
Function Declaration | ✅ Yes | ✅ Yes |
Function Expression (var ) | ✅ Yes | ❌ No (undefined) |
Would you like more examples or a deep dive into TDZ? 🚀